//订单确认页面
var basePage = require('../../common/BasePage');
Page({
    behaviors: [basePage],
    data: {
        /**要访问的仓库 */
        wh_id:1,
        /**当前选中的仓库信息 */
        warehouse:{},
        /**支付凭证 */
        pay_cert: {
            /**完整图片路径 */
            url: '/assets/photo.png',
            /**后台地址 */
            photo: '',
            /**''未选择;loading 上传中;error 上传失败;ok 上传成功 */
            state: '',
        },
        /**密码设置弹窗 */
        editPassPop: false,
        /**重新设置的密码 */
        repass: '',
        /**支付参数 */
        payData: {},
        /**支付密码 */
        password: '',
        /**是否显示密码输入框 */
        passPop: false,
        /**支付方式 */
        pay: 'coin',
        /**订单信息 */
        order: {},
        /**地址信息 */
        m_addr: null,
        /**选中的优惠券信息 */
        coupon: {
            cid: 0
        },
        show: false,
        showPay:false,
        price: 0,
        /**设置提交按钮状态 */
        loading:false,
        coupon_radio: '', //优惠券选中项
        /**是否可以提交 */
        can_submit:true,
		    from:"yuyue"
    },
    onLoad: function (option) {
        // console.log(option.query);
		this.setData({
			wh_id:option.wh_id,
			from:option.from
		})
        let that = this;
        const eventChannel = this.getOpenerEventChannel();
        eventChannel.on('orderPreData', function (data) {
			      console.log("预售订单",data)
            that.data.warehouse=getApp().globalData.warehouse;
            if(data.data.wh_id!=1&&data.data.wh_id!=4){
              that.setData({
                  pay: 'wxpay',
              })
          }
            that.setData({
                wh_id:data.data.wh_id,
                m_addr: data.data.m_addr,
                order: data.data,
                coupon: that.data.coupon
            })

        })
    },
    /**
     * 凭证上传
     */
    img_upload(e) {
        let that = this;
        /**上传图片的对象 */
        let img = e.currentTarget.dataset.img;
        wx.chooseImage({
            count: 1,
            sizeType: ['compressed'],
            sourceType: ['album', 'camera'],
            success(imgRes) {
                // tempFilePath可以作为img标签的src属性显示图片
                const tempFilePaths = imgRes.tempFilePaths;
                console.log("tempFilePaths", tempFilePaths);
                let photo = {}; //用于更新视图诗句
                let id_photo_front = photo[img] = that.data[img];
                id_photo_front.url = tempFilePaths[0];
                id_photo_front.state = "loading";
                console.log("photo", photo)
                that.setData(photo)
                wx.uploadFile({
                    filePath: tempFilePaths[0],
                    name: 'image',
                    url: that.data.host + '/home/upload/image',
                    formData: {
                        from: 'verify'
                    },
                    success(res) {
                        id_photo_front.state = "error";
                        // id_photo_front.photo='';
                        // console.log("home/upload/image", res);
                        if (res.statusCode != 200) {
                            return wx.showModal({
                                showCancel: false,
                                content: res.errMsg || '上传失败',
                            })
                        }
                        let resObj = JSON.parse(res.data);
                        if (resObj.code) {
                            return wx.showToast({
                                title: resObj.msg,
                                icon: 'none'
                            })
                        }
                        id_photo_front.state = "ok";
                        id_photo_front.photo = resObj.data.path;

                    },
                    fail() {
                        id_photo_front.state = "error";
                        wx.showModal({
                            showCancel: false,
                            content: '上传接口异常',
                        })
                    },
                    complete() {
                        that.setData(photo)
                    }
                });
            },
            fail(e) {
                wx.showToast({
                    title: e.errMsg || '调用微信文件失败',
                    icon: 'none'
                })
                // console.log(e);
            }
        })
    },
    /**设置支付密码 */
    edit_pass() {
        this.request({
            url: this.data.host + '/home/user/editPasswd',
            data: {
                password: this.data.repass
            },
            method: 'post'
        }, res => {
            wx.showToast({
                title: '设置成功',
                icon: 'none'
            });
            this.setData({
                editPassPop: false
            })
        });
    },
    pay_click(e) {
      this.setData({
        showPay:true
      })
          
      },
    /**
     * 确认订单（立即支付）
     */
    submit_order() {
        let that=this;
        if(!this.data.can_submit){
            return wx.showToast({
              title: '请勿重复提交',
              icon:'none'
            })
        }
        this.data.can_submit=false;
        setTimeout(() => {
            this.data.can_submit=true
        }, 1000);
        this.setData({
            loading:true,
            showPay:false
        })
  //       let tip='此商品由'+this.data.warehouse.title+"派送，请确认";
  //       if(this.data.warehouse.wh_id==1){
  //           tip='此商品由'+this.data.warehouse.title+"派送，需要30扎混搭发货，请确认";
  //       }
  //       wx.showModal({
          
  //           cancelText: '取消',
         
  //           confirmText: '确认',
  //           content: tip,
          
  //           showCancel: true,
  //           title: '提示',
  //           success: (result) => {
  //             if (result.confirm){
                  
  //             }
  //           },
  
  //         })

        this.req_submit()
    },
    req_submit(){
        if (this.data.payData && this.data.payData.order_id) {
            return this.check_pay(); //已经下单成功，直接进行支付
        }
        //请求购物车数据
        this.request({
            url: this.data.host + '/home/yuyue/handle?wh_id='+this.data.wh_id,
            loadingTip:"正在提交",
            data: {
                addr_id: this.data.m_addr.addr_id,
                yy_id: this.data.order.yy_id,
				nums:this.data.order.nums,
				from:this.data.from
            },
            method: 'post'
        }, this.submit_ok,null,res=>{
            this.setData({
                loading:false,
            })
        });
    },
    submit_ok(obj) {
        // console.log("submit_ok", obj);

        this.data.payData = {
            order_id: obj.data.order_id,
            code: this.data.pay
        }
        this.check_pay();
    },
    /**检查支付方式 */
    check_pay() {
        this.pay_order()
    },
    submit_pass() {
        if (!this.data.password) {
            return wx.showToast({
                title: '请先输入密码',
                icon: 'none'
            })
        }
        this.setData({
            passPop: false
        })
        this.data.payData.password = this.data.password;
        this.pay_order()
        // console.log("password",this.data.password);
        // console.log("payData",this.data.payData);
    },
    /**
     * 支付订单
     */
    pay_order() {
        // let that=this;
        this.data.pay_cert.photo ? this.data.payData.pay_cert = this.data.pay_cert.photo : '';
        this.request({
            url: this.data.host + '/home/payment/order',
            loadingTip:"正在提交",
            method: "POST",
            data: this.data.payData
        }, res => {
            //  console.log("payment/order",res,this.data.payData.code);
            if (this.data.payData.code == 'wxpay') { //调用微信支付
                wx.requestPayment({
                    ...res.data.pay_data,
                    success(res) {
                        wx.showToast({
                            title: '支付成功',
                        })

                    },
                    fail(err) {
                        wx.showToast({
                            title: '支付失败',
                            icon: 'none'
                        })
                        console.error('pay fail', err)
                    },
                    complete() {
                        wx.redirectTo({
                            url: '/pages/cls/my_order/order',
                        })
                    }
                })
            } else {
                wx.redirectTo({
                    url: '/pages/cls/my_order/order',
                })
            }
            //  return;

        },null,res=>{
            this.setData({
                loading:false,
            })
        });
    },
    addr_click() {
        let that = this;
        wx.navigateTo({
            url: '/pages/addr/AddrList',
            events: {
                change_addr: function (data) {
                    console.log("change_addr", data);
                    that.setData({
                        m_addr: data.addr
                    })
                }
            }
        })
    },
    open_van_action_sheet() {
        this.setData({
            show: true
        });
    },
    onClose() {
        this.setData({
            show: false
        });
    },
    onSelect(event) {
        console.log(event.detail);
    },
    onClick(event) {
        let name = event.currentTarget.dataset.name;
        this.data.payData.code = name;
        this.setData({
            pay: name,
        })
    },
    clickUpload() {
        // if (parseInt(this.data.radio) !== 3) {
        //     wx.showToast({
        //         title: '仅线下支付允许上传凭证',
        //         icon: 'none'
        //     })
        // }
    },
    radioChange(e) {
        console.log("radioChange", e)
        this.setData({
            coupon_radio: e.detail,
            show: false
        })
    },

    coupon_click(e) {
        console.log("coupon", e.currentTarget.dataset.coupon);
        let coupon = e.currentTarget.dataset.coupon;
        console.log("order", this.data.order);
        let order = this.data.order;
        order.total_youhui = coupon.coupon_amount;
        order.amount = order.total_price - coupon.coupon_amount;
        //amount=total_price-total_youhui
        // order.total_youhui=coupon.coupon_amount;
        this.setData({
            coupon,
            order,
            show: false
        })
    },
    /**显示密码重置弹窗 */
    show_edit() {
        this.setData({
            editPassPop: true
        })
    }
})